package com.niubility.server.Impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class QiniuUtilService implements IQiniuUtilService {
    private String ACCESS_KEY="HutmmyGMq9MWIw--AoqnwWeutp2vljQP0DqoJXml";
    private String SECRET_KEY="GEoY1sfbNBnwYMHIBKJBlqYGv813xNw6LkqLbEnx";
    private String bucketname="niubility1";
    private String picURL="http://p3iyvwddr.bkt.clouddn.com/";
    //设置好账号的ACCESS_KEY和SECRET_KEY
    //String ACCESS_KEY = Demo.Config.getValue("qinNiu.ACCESS_KEY"); //这两个登录七牛 账号里面可以找到
    //String SECRET_KEY = Demo.Config.getValue("qinNiu.SECRET_KEY");

    //要上传的空间
    //String bucketname = Demo.Config.getValue("qinNiu.bucketname"); //对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置公开）
   // String URL= Demo.Config.getValue("qinNiu.picURL");
    //上传到七牛后保存的文件名
    // String key = "daimo6.png";
    //上传文件的路径
    //密钥配置
    //创建上传对象
    Configuration cfg = new Configuration(Zone.zone1());
    UploadManager uploadManager = new UploadManager(cfg);


    /**
     * 上传图片到七牛云
     * @param FilePath（本地文件路径）
     * @return
     * @throws IOException
     */
    public String upload(String FilePath) throws IOException {
        if (!FilePath.contains("p3iyvwddr.bkt.clouddn.com")) {
            System.out.println(FilePath);
            //Zone au = Zone.autoZone();
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(bucketname);
            String key=null;
            if(FilePath.contains("\\")) {
                key = FilePath.substring(FilePath.lastIndexOf("\\") + 1);
            }else{
                key = FilePath.substring(FilePath.lastIndexOf("/") + 1);
            }
            StringBuffer bf=new StringBuffer();
            StringBuffer b=bf.append(picURL);
            StringBuffer picURL= b.append(key);
            try {
                Response response = uploadManager.put(FilePath, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
               System.out.println(putRet.key);
               System.out.println(picURL);
               File file=new File(FilePath);
               if(file.exists()){
                   file.delete();
               }
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
            return picURL.toString();
        } else {
            return FilePath;
        }
    }

    /**
     * 删除一个七牛云上的图片
     * @param path 图片在七牛云上的路径
     * @throws IOException
     */
    public void deletePic(String path)throws IOException{
        //...其他参数参考类注释
        String key = path.substring(path.lastIndexOf("/") + 1);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucketname , key);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

    /**
     * 批量删除七牛云上的图片
     */
    public void deleteNum(String [] str){
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            //单次批量请求的文件数量不得超过1000
            String[] keyList = new String[str.length];
            for(int i=0;i<str.length;i++){
                String key = str[i].substring(str[i].lastIndexOf("/") + 1);
                keyList[i]=key;
            }
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucketname, keyList);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < keyList.length; i++) {
                BatchStatus status = batchStatusList[i];
                String key = keyList[i];
                System.out.print(key + "\t");
                if (status.code == 200) {
                    System.out.println("delete success");
                } else {
                    System.out.println(status.data.error);
                }
            }
        } catch (QiniuException ex) {
            System.err.println(ex.response.toString());
        }
    }
}
